﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WooCoo.Data;

namespace WooCoo.ObjectModel
{
    public partial class EntityList<T>
    {
        protected virtual void DataPortal_Create() 
        {
            DataPortal_Update();
        }

        protected virtual void DataPortal_Fetch(object criteria)
        {
            //var cri = criteria as Criteria;
            //this.GetRepository().GetEntityList<T>(this, cri);
        }

        /// <summary>
        /// 更新方法，在本方法中并未新起事务，如果为子对象时，事务由父对象发起。
        /// 当只为列表对象时，可不需要事务。
        /// </summary>
        protected virtual void DataPortal_Update()
        {
            this.GetRepository().SaveChanges(this);
        }

        #region Save
        /// <summary>
        /// 子对象的客户端保存方法，
        /// </summary>        
        public void Save(DataPortal.DataPortalClient client = null)
        {
            if (this.Parent!=null)
            {
                //子对象不可单独更新
                throw new NotSupportedException(Localizer.Active.GetLocalizeString(StringID.NoSaveChildException));
            }            
            if (this.IsDirty)
            {
                if (client == null)
                    client = DataPortal.DataPortalClient.Default;
                //纯列表对象，只需要进行单对象更新
                this.SaveChild(client);
            }
        }

        private void SaveChild(DataPortal.DataPortalClient client = null)
        {
            foreach (var child in DeletedList)
                if (!child.IsNew)
                {
                    child.Save(client, true);
                    //DataPortal.Update(child);
                }
            foreach (var child in this)
                if (child.IsDirty)
                {
                    child.Save(client,true);
                }
            DeletedList.Clear();
        }
        #endregion

    }
}
